// Dashboard初始化脚本
$(document).ready(function() {
    console.log('Dashboard页面加载完成');

    // 检查用户登录状态
    checkUserLogin();

    // 更新当前日期
    updateCurrentDate();

    // 加载统计数据
    loadStatistics();

    // 绑定退出登录事件
    $('#logoutBtn').on('click', function() {
        if (confirm('确定要退出登录吗？')) {
            // 获取当前用户信息
            var userInfoStr = localStorage.getItem('userInfo');
            var username = '';
            if (userInfoStr) {
                try {
                    var userInfo = JSON.parse(userInfoStr);
                    username = userInfo.username;
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                }
            }
            
            $.post('/user/logout', {username: username}, function(res) {
                if (res.code === 200) {
                    // 清除本地存储的用户信息
                    localStorage.removeItem('userInfo');
                    alert('退出成功');
                    window.location.href = 'login.html';
                } else {
                    alert(res.message || '退出失败');
                }
            }).fail(function() {
                alert('网络错误，请稍后重试');
            });
        }
    });

    // 绑定导航菜单事件
    $('.layui-nav-item a').on('click', function() {
        var module = $(this).data('module');
        if (module) {
            loadModule(module);
        }
    });
});

function updateCurrentDate() {
    var now = new Date();
    var options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
    };
    var dateStr = now.toLocaleDateString('zh-CN', options);
    $('#currentDate').text(dateStr);
}

function loadStatistics() {
    console.log('开始加载统计数据');

    // 加载图书统计
    $.get('/book/list', {pageSize: 1}, function(res) {
        console.log('图书统计响应:', res);
        if (res.code === 200 && res.data) {
            $('#totalBooks').text(res.data.total || 0);
        } else {
            $('#totalBooks').text('0');
        }
    }).fail(function() {
        $('#totalBooks').text('0');
    });

    // 加载用户统计
    $.get('/user/list', {pageSize: 1}, function(res) {
        console.log('用户统计响应:', res);
        if (res.code === 200 && res.data) {
            $('#totalUsers').text(res.data.total || 0);
        } else {
            $('#totalUsers').text('0');
        }
    }).fail(function() {
        $('#totalUsers').text('0');
    });

    // 加载借阅统计
    $.get('/borrow/list', {pageSize: 1}, function(res) {
        console.log('借阅统计响应:', res);
        if (res.code === 200 && res.data) {
            var borrowedCount = 0;
            var overdueCount = 0;

            if (res.data.records) {
                res.data.records.forEach(function(item) {
                    if (item.status === 0) {
                        borrowedCount++;
                    } else if (item.status === 2) {
                        overdueCount++;
                    }
                });
            }

            $('#borrowedBooks').text(borrowedCount);
            $('#overdueBooks').text(overdueCount);
        } else {
            $('#borrowedBooks').text('0');
            $('#overdueBooks').text('0');
        }
    }).fail(function() {
        $('#borrowedBooks').text('0');
        $('#overdueBooks').text('0');
    });
}

function checkUserLogin() {
    console.log('检查用户登录状态');
    
    // 从localStorage获取用户信息
    var userInfoStr = localStorage.getItem('userInfo');
    if (!userInfoStr) {
        console.log('未找到用户信息，跳转到登录页面');
        alert('请先登录');
        window.location.href = 'login.html';
        return;
    }
    
    try {
        var userInfo = JSON.parse(userInfoStr);
        console.log('当前用户信息:', userInfo);
        
        // 显示用户信息
        if (userInfo.username) {
            $('.user-name').text(userInfo.username);
            $('.user-role').text(userInfo.role === 1 ? '管理员' : '普通用户');
        }
        
        // 根据用户角色显示/隐藏某些功能
        if (userInfo.role !== 1) {
            // 普通用户隐藏管理员功能
            $('.admin-only').hide();
        }
        
    } catch (e) {
        console.error('解析用户信息失败:', e);
        alert('用户信息异常，请重新登录');
        localStorage.removeItem('userInfo');
        window.location.href = 'login.html';
    }
}

function loadModule(moduleName) {
    console.log('加载模块:', moduleName);

    // 隐藏所有模块
    $('[id$="Module"]').hide();

    // 显示当前模块
    $('#' + moduleName + 'Module').show();

    // 更新导航状态
    $('.layui-nav-item').removeClass('layui-this');
    $('[data-module="' + moduleName + '"]').parent().addClass('layui-this');

    // 初始化对应模块的表格
    if (moduleName === 'book') {
        initBookTable();
    } else if (moduleName === 'user') {
        initUserTable();
    } else if (moduleName === 'borrow') {
        initBorrowTable();
    } else if (moduleName === 'category') {
        initCategoryTable();
    } else if (moduleName === 'publisher') {
        initPublisherTable();
    } else if (moduleName === 'author') {
        initAuthorTable();
    }
}

// 初始化图书表格
function initBookTable() {
    console.log('初始化图书表格');
    if (typeof layui !== 'undefined' && layui.table) {
        layui.use(['table', 'form', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            
            var tableIns = table.render({
                elem: '#bookTable',
                url: '/book/list',
                method: 'get',
                toolbar: '#bookToolbar',
                defaultToolbar: ['filter', 'exports', 'print'],
                parseData: function(res) {
                    return {
                        "code": res.code === 200 ? 0 : res.code,
                        "msg": res.message,
                        "count": res.data ? res.data.total : 0,
                        "data": res.data ? res.data.records : []
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'isbn', title: 'ISBN', width: 120},
                    {field: 'title', title: '书名', width: 200},
                    {field: 'subtitle', title: '副标题', width: 150},
                    {field: 'price', title: '价格', width: 80},
                    {field: 'stock', title: '库存', width: 80},
                    {field: 'borrowedCount', title: '借阅次数', width: 100},
                    {field: 'publishDate', title: '出版日期', width: 120, templet: function(d) {
                        return d.publishDate ? new Date(d.publishDate).toLocaleDateString() : '';
                    }},
                    {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#bookBar'}
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100]
            });

            // 绑定表格工具条事件
            table.on('tool(bookTable)', function(obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    showBookDialog(data);
                } else if (obj.event === 'del') {
                    layer.confirm('确定删除此图书？', function(index) {
                        $.post('/book/delete', {id: data.id}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                obj.del();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });

            // 绑定工具栏按钮事件
            table.on('toolbar(bookTable)', function(obj) {
                if (obj.event === 'add') {
                    showBookDialog();
                } else if (obj.event === 'batchDel') {
                    var checkStatus = table.checkStatus('bookTable');
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg('请选择要删除的数据', {icon: 2});
                        return;
                    }
                    
                    var ids = data.map(function(item) {
                        return item.id;
                    });
                    
                    layer.confirm('确定要删除选中的图书吗？', function(index) {
                        $.post('/book/deleteBatch', {ids: ids}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                tableIns.reload();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });
        });
    }
}

// 显示图书对话框
function showBookDialog(data) {
    var title = data ? '编辑图书' : '新增图书';
    var bookHtml = `
        <form class="layui-form" id="bookForm" style="padding: 20px;">
            <input type="hidden" name="id" value="${data ? data.id : ''}">
            <div class="layui-form-item">
                <label class="layui-form-label">ISBN</label>
                <div class="layui-input-block">
                    <input type="text" name="isbn" required lay-verify="required" placeholder="请输入ISBN" value="${data ? data.isbn : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">书名</label>
                <div class="layui-input-block">
                    <input type="text" name="title" required lay-verify="required" placeholder="请输入书名" value="${data ? data.title : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">副标题</label>
                <div class="layui-input-block">
                    <input type="text" name="subtitle" placeholder="请输入副标题" value="${data ? data.subtitle : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">价格</label>
                <div class="layui-input-block">
                    <input type="number" name="price" step="0.01" placeholder="请输入价格" value="${data ? data.price : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">库存</label>
                <div class="layui-input-block">
                    <input type="number" name="stock" placeholder="请输入库存" value="${data ? data.stock : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">页数</label>
                <div class="layui-input-block">
                    <input type="number" name="pageCount" placeholder="请输入页数" value="${data ? data.pageCount : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">语言</label>
                <div class="layui-input-block">
                    <input type="text" name="language" placeholder="请输入语言" value="${data ? data.language : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">简介</label>
                <div class="layui-input-block">
                    <textarea name="description" placeholder="请输入图书简介" class="layui-textarea">${data ? data.description : ''}</textarea>
                </div>
            </div>
        </form>
    `;

    layui.use(['layer', 'form'], function() {
        var layer = layui.layer;
        var form = layui.form;
        
        var dialog = layer.open({
            type: 1,
            title: title,
            area: ['700px', '600px'],
            content: bookHtml,
            btn: ['确定', '取消'],
            success: function(layero, index) {
                form.render();
            },
            yes: function(index, layero) {
                var formData = form.val('bookForm');
                
                // 发送请求
                var url = formData.id ? '/book/update' : '/book/add';
                $.post(url, formData, function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '修改成功' : '添加成功', {icon: 1});
                        layer.close(index);
                        // 重新加载表格
                        if (typeof layui !== 'undefined' && layui.table) {
                            layui.table.reload('bookTable');
                        }
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }
        });
    });
}

// 初始化用户表格
function initUserTable() {
    console.log('初始化用户表格');
    if (typeof layui !== 'undefined' && layui.table) {
        layui.use(['table', 'form', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            
            var tableIns = table.render({
                elem: '#userTable',
                url: '/user/list',
                method: 'get',
                toolbar: '#userToolbar',
                defaultToolbar: ['filter', 'exports', 'print'],
                parseData: function(res) {
                    return {
                        "code": res.code === 200 ? 0 : res.code,
                        "msg": res.message,
                        "count": res.data ? res.data.total : 0,
                        "data": res.data ? res.data.records : []
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'username', title: '用户名', width: 120},
                    {field: 'realName', title: '真实姓名', width: 120},
                    {field: 'phone', title: '手机号', width: 120},
                    {field: 'email', title: '邮箱', width: 150},
                    {field: 'role', title: '角色', width: 80, templet: function(d) {
                        return d.role === 1 ? '管理员' : '普通用户';
                    }},
                    {field: 'status', title: '状态', width: 80, templet: function(d) {
                        return d.status === 1 ? '正常' : '禁用';
                    }},
                    {field: 'createTime', title: '创建时间', width: 150, templet: function(d) {
                        return d.createTime ? new Date(d.createTime).toLocaleString() : '';
                    }},
                    {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#userBar'}
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100]
            });

            // 绑定表格工具条事件
            table.on('tool(userTable)', function(obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    showUserDialog(data);
                } else if (obj.event === 'del') {
                    layer.confirm('确定删除此用户？', function(index) {
                        $.post('/user/delete', {id: data.id}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                obj.del();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });

            // 绑定工具栏按钮事件
            table.on('toolbar(userTable)', function(obj) {
                if (obj.event === 'add') {
                    showUserDialog();
                } else if (obj.event === 'batchDel') {
                    var checkStatus = table.checkStatus('userTable');
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg('请选择要删除的数据', {icon: 2});
                        return;
                    }
                    
                    var ids = data.map(function(item) {
                        return item.id;
                    });
                    
                    layer.confirm('确定要删除选中的用户吗？', function(index) {
                        $.post('/user/deleteBatch', {ids: ids}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                tableIns.reload();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });
        });
    }
}

// 显示用户对话框
function showUserDialog(data) {
    var title = data ? '编辑用户' : '新增用户';
    var userHtml = `
        <form class="layui-form" id="userForm" style="padding: 20px;">
            <input type="hidden" name="id" value="${data ? data.id : ''}">
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" value="${data ? data.username : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" ${data ? '' : 'required lay-verify="required"'} placeholder="${data ? '不修改请留空' : '请输入密码'}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">真实姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="realName" placeholder="请输入真实姓名" value="${data ? data.realName : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">手机号</label>
                <div class="layui-input-block">
                    <input type="text" name="phone" placeholder="请输入手机号" value="${data ? data.phone : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="email" name="email" placeholder="请输入邮箱" value="${data ? data.email : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">角色</label>
                <div class="layui-input-block">
                    <select name="role">
                        <option value="0" ${data && data.role === 0 ? 'selected' : ''}>普通用户</option>
                        <option value="1" ${data && data.role === 1 ? 'selected' : ''}>管理员</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <select name="status">
                        <option value="1" ${data && data.status === 1 ? 'selected' : ''}>正常</option>
                        <option value="0" ${data && data.status === 0 ? 'selected' : ''}>禁用</option>
                    </select>
                </div>
            </div>
        </form>
    `;

    layui.use(['layer', 'form'], function() {
        var layer = layui.layer;
        var form = layui.form;
        
        var dialog = layer.open({
            type: 1,
            title: title,
            area: ['600px', '550px'],
            content: userHtml,
            btn: ['确定', '取消'],
            success: function(layero, index) {
                form.render();
            },
            yes: function(index, layero) {
                var formData = form.val('userForm');
                
                // 发送请求
                var url = formData.id ? '/user/update' : '/user/add';
                $.post(url, formData, function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '修改成功' : '添加成功', {icon: 1});
                        layer.close(index);
                        // 重新加载表格
                        if (typeof layui !== 'undefined' && layui.table) {
                            layui.table.reload('userTable');
                        }
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }
        });
    });
}

// 初始化借阅表格
function initBorrowTable() {
    console.log('初始化借阅表格');
    if (typeof layui !== 'undefined' && layui.table) {
        layui.use(['table', 'form', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            
            var tableIns = table.render({
                elem: '#borrowTable',
                url: '/borrow/list',
                method: 'get',
                toolbar: '#borrowToolbar',
                defaultToolbar: ['filter', 'exports', 'print'],
                parseData: function(res) {
                    return {
                        "code": res.code === 200 ? 0 : res.code,
                        "msg": res.message,
                        "count": res.data ? res.data.total : 0,
                        "data": res.data ? res.data.records : []
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'bookTitle', title: '图书名称', width: 150},
                    {field: 'userName', title: '借阅人', width: 100},
                    {field: 'borrowDate', title: '借阅日期', width: 120, templet: function(d) {
                        return d.borrowDate ? new Date(d.borrowDate).toLocaleDateString() : '';
                    }},
                    {field: 'dueDate', title: '应还日期', width: 120, templet: function(d) {
                        return d.dueDate ? new Date(d.dueDate).toLocaleDateString() : '';
                    }},
                    {field: 'returnDate', title: '实际归还日期', width: 120, templet: function(d) {
                        return d.returnDate ? new Date(d.returnDate).toLocaleDateString() : '';
                    }},
                    {field: 'status', title: '状态', width: 80, templet: function(d) {
                        if (d.status === 0) return '借阅中';
                        if (d.status === 1) return '已归还';
                        if (d.status === 2) return '逾期';
                        return '未知';
                    }},
                    {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#borrowBar'}
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100]
            });

            // 绑定表格工具条事件
            table.on('tool(borrowTable)', function(obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    showBorrowDialog(data);
                } else if (obj.event === 'del') {
                    layer.confirm('确定删除此借阅记录？', function(index) {
                        $.post('/borrow/delete', {id: data.id}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                obj.del();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });

            // 绑定工具栏按钮事件
            table.on('toolbar(borrowTable)', function(obj) {
                if (obj.event === 'add') {
                    showBorrowDialog();
                } else if (obj.event === 'batchDel') {
                    var checkStatus = table.checkStatus('borrowTable');
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg('请选择要删除的数据', {icon: 2});
                        return;
                    }
                    
                    var ids = data.map(function(item) {
                        return item.id;
                    });
                    
                    layer.confirm('确定要删除选中的借阅记录吗？', function(index) {
                        $.post('/borrow/deleteBatch', {ids: ids}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                tableIns.reload();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });
        });
    }
}

// 显示借阅对话框
function showBorrowDialog(data) {
    var title = data ? '编辑借阅记录' : '新增借阅记录';
    var borrowHtml = `
        <form class="layui-form" id="borrowForm" style="padding: 20px;">
            <input type="hidden" name="id" value="${data ? data.id : ''}">
            <div class="layui-form-item">
                <label class="layui-form-label">图书ID</label>
                <div class="layui-input-block">
                    <input type="number" name="bookId" required lay-verify="required" placeholder="请输入图书ID" value="${data ? data.bookId : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">用户ID</label>
                <div class="layui-input-block">
                    <input type="number" name="userId" required lay-verify="required" placeholder="请输入用户ID" value="${data ? data.userId : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">借阅日期</label>
                <div class="layui-input-block">
                    <input type="text" name="borrowDate" id="borrowDate" placeholder="请选择借阅日期" value="${data ? data.borrowDate : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">应还日期</label>
                <div class="layui-input-block">
                    <input type="text" name="dueDate" id="dueDate" placeholder="请选择应还日期" value="${data ? data.dueDate : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <select name="status">
                        <option value="0" ${data && data.status === 0 ? 'selected' : ''}>借阅中</option>
                        <option value="1" ${data && data.status === 1 ? 'selected' : ''}>已归还</option>
                        <option value="2" ${data && data.status === 2 ? 'selected' : ''}>逾期</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入备注" class="layui-textarea">${data ? data.remark : ''}</textarea>
                </div>
            </div>
        </form>
    `;

    layui.use(['layer', 'form', 'laydate'], function() {
        var layer = layui.layer;
        var form = layui.form;
        var laydate = layui.laydate;
        
        var dialog = layer.open({
            type: 1,
            title: title,
            area: ['600px', '550px'],
            content: borrowHtml,
            btn: ['确定', '取消'],
            success: function(layero, index) {
                // 初始化日期选择器
                laydate.render({
                    elem: '#borrowDate'
                });
                laydate.render({
                    elem: '#dueDate'
                });
                form.render();
            },
            yes: function(index, layero) {
                var formData = form.val('borrowForm');
                
                // 发送请求
                var url = formData.id ? '/borrow/update' : '/borrow/add';
                $.post(url, formData, function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '修改成功' : '添加成功', {icon: 1});
                        layer.close(index);
                        // 重新加载表格
                        if (typeof layui !== 'undefined' && layui.table) {
                            layui.table.reload('borrowTable');
                        }
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }
        });
    });
}

// 初始化分类表格
function initCategoryTable() {
    console.log('初始化分类表格');
    if (typeof layui !== 'undefined' && layui.table) {
        layui.use(['table', 'form', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            
            var tableIns = table.render({
                elem: '#categoryTable',
                url: '/category/list',
                method: 'get',
                toolbar: '#categoryToolbar',
                defaultToolbar: ['filter', 'exports', 'print'],
                parseData: function(res) {
                    return {
                        "code": res.code === 200 ? 0 : res.code,
                        "msg": res.message,
                        "count": res.data ? res.data.total : 0,
                        "data": res.data ? res.data.records : []
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'name', title: '分类名称', width: 150},
                    {field: 'description', title: '描述', width: 200},
                    {field: 'status', title: '状态', width: 80, templet: function(d) {
                        return d.status === 1 ? '启用' : '禁用';
                    }},
                    {field: 'createTime', title: '创建时间', width: 150, templet: function(d) {
                        return d.createTime ? new Date(d.createTime).toLocaleString() : '';
                    }},
                    {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#categoryBar'}
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100]
            });

            // 绑定表格工具条事件
            table.on('tool(categoryTable)', function(obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    showCategoryDialog(data);
                } else if (obj.event === 'del') {
                    layer.confirm('确定删除此分类？', function(index) {
                        $.post('/category/delete', {id: data.id}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                obj.del();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });

            // 绑定工具栏按钮事件
            table.on('toolbar(categoryTable)', function(obj) {
                if (obj.event === 'add') {
                    showCategoryDialog();
                } else if (obj.event === 'batchDel') {
                    var checkStatus = table.checkStatus('categoryTable');
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg('请选择要删除的数据', {icon: 2});
                        return;
                    }
                    
                    var ids = data.map(function(item) {
                        return item.id;
                    });
                    
                    layer.confirm('确定要删除选中的分类吗？', function(index) {
                        $.post('/category/deleteBatch', {ids: ids}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                tableIns.reload();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });
        });
    }
}

// 显示分类对话框
function showCategoryDialog(data) {
    var title = data ? '编辑分类' : '新增分类';
    var categoryHtml = `
        <form class="layui-form" id="categoryForm" style="padding: 20px;">
            <input type="hidden" name="id" value="${data ? data.id : ''}">
            <div class="layui-form-item">
                <label class="layui-form-label">分类名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="请输入分类名称" value="${data ? data.name : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <textarea name="description" placeholder="请输入分类描述" class="layui-textarea">${data ? data.description : ''}</textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <select name="status">
                        <option value="1" ${data && data.status === 1 ? 'selected' : ''}>启用</option>
                        <option value="0" ${data && data.status === 0 ? 'selected' : ''}>禁用</option>
                    </select>
                </div>
            </div>
        </form>
    `;

    layui.use(['layer', 'form'], function() {
        var layer = layui.layer;
        var form = layui.form;
        
        var dialog = layer.open({
            type: 1,
            title: title,
            area: ['500px', '450px'],
            content: categoryHtml,
            btn: ['确定', '取消'],
            success: function(layero, index) {
                form.render();
            },
            yes: function(index, layero) {
                var formData = form.val('categoryForm');
                
                // 发送请求
                var url = formData.id ? '/category/update' : '/category/add';
                $.post(url, formData, function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '修改成功' : '添加成功', {icon: 1});
                        layer.close(index);
                        // 重新加载表格
                        if (typeof layui !== 'undefined' && layui.table) {
                            layui.table.reload('categoryTable');
                        }
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }
        });
    });
}

// 初始化出版社表格
function initPublisherTable() {
    console.log('初始化出版社表格');
    if (typeof layui !== 'undefined' && layui.table) {
        layui.use(['table', 'form', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            
            var tableIns = table.render({
                elem: '#publisherTable',
                url: '/publisher/list',
                method: 'get',
                toolbar: '#publisherToolbar',
                defaultToolbar: ['filter', 'exports', 'print'],
                parseData: function(res) {
                    return {
                        "code": res.code === 200 ? 0 : res.code,
                        "msg": res.message,
                        "count": res.data ? res.data.total : 0,
                        "data": res.data ? res.data.records : []
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'name', title: '出版社名称', width: 150},
                    {field: 'address', title: '地址', width: 200},
                    {field: 'phone', title: '电话', width: 120},
                    {field: 'email', title: '邮箱', width: 150},
                    {field: 'status', title: '状态', width: 80, templet: function(d) {
                        return d.status === 1 ? '启用' : '禁用';
                    }},
                    {field: 'createTime', title: '创建时间', width: 150, templet: function(d) {
                        return d.createTime ? new Date(d.createTime).toLocaleString() : '';
                    }},
                    {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#publisherBar'}
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100]
            });

            // 绑定表格工具条事件
            table.on('tool(publisherTable)', function(obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    showPublisherDialog(data);
                } else if (obj.event === 'del') {
                    layer.confirm('确定删除此出版社？', function(index) {
                        $.post('/publisher/delete', {id: data.id}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                obj.del();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });

            // 绑定工具栏按钮事件
            table.on('toolbar(publisherTable)', function(obj) {
                if (obj.event === 'add') {
                    showPublisherDialog();
                } else if (obj.event === 'batchDel') {
                    var checkStatus = table.checkStatus('publisherTable');
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg('请选择要删除的数据', {icon: 2});
                        return;
                    }
                    
                    var ids = data.map(function(item) {
                        return item.id;
                    });
                    
                    layer.confirm('确定要删除选中的出版社吗？', function(index) {
                        $.post('/publisher/deleteBatch', {ids: ids}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                tableIns.reload();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });
        });
    }
}

// 显示出版社对话框
function showPublisherDialog(data) {
    var title = data ? '编辑出版社' : '新增出版社';
    var publisherHtml = `
        <form class="layui-form" id="publisherForm" style="padding: 20px;">
            <input type="hidden" name="id" value="${data ? data.id : ''}">
            <div class="layui-form-item">
                <label class="layui-form-label">出版社名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="请输入出版社名称" value="${data ? data.name : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">地址</label>
                <div class="layui-input-block">
                    <input type="text" name="address" placeholder="请输入地址" value="${data ? data.address : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">电话</label>
                <div class="layui-input-block">
                    <input type="text" name="phone" placeholder="请输入电话" value="${data ? data.phone : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="email" name="email" placeholder="请输入邮箱" value="${data ? data.email : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <select name="status">
                        <option value="1" ${data && data.status === 1 ? 'selected' : ''}>启用</option>
                        <option value="0" ${data && data.status === 0 ? 'selected' : ''}>禁用</option>
                    </select>
                </div>
            </div>
        </form>
    `;

    layui.use(['layer', 'form'], function() {
        var layer = layui.layer;
        var form = layui.form;
        
        var dialog = layer.open({
            type: 1,
            title: title,
            area: ['500px', '500px'],
            content: publisherHtml,
            btn: ['确定', '取消'],
            success: function(layero, index) {
                form.render();
            },
            yes: function(index, layero) {
                var formData = form.val('publisherForm');
                
                // 发送请求
                var url = formData.id ? '/publisher/update' : '/publisher/add';
                $.post(url, formData, function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '修改成功' : '添加成功', {icon: 1});
                        layer.close(index);
                        // 重新加载表格
                        if (typeof layui !== 'undefined' && layui.table) {
                            layui.table.reload('publisherTable');
                        }
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }
        });
    });
}

// 初始化作者表格
function initAuthorTable() {
    console.log('初始化作者表格');
    if (typeof layui !== 'undefined' && layui.table) {
        layui.use(['table', 'form', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            
            var tableIns = table.render({
                elem: '#authorTable',
                url: '/author/list',
                method: 'get',
                toolbar: '#authorToolbar',
                defaultToolbar: ['filter', 'exports', 'print'],
                parseData: function(res) {
                    return {
                        "code": res.code === 200 ? 0 : res.code,
                        "msg": res.message,
                        "count": res.data ? res.data.total : 0,
                        "data": res.data ? res.data.records : []
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'name', title: '作者姓名', width: 120},
                    {field: 'biography', title: '简介', width: 200},
                    {field: 'nationality', title: '国籍', width: 100},
                    {field: 'email', title: '邮箱', width: 150},
                    {field: 'status', title: '状态', width: 80, templet: function(d) {
                        return d.status === 1 ? '启用' : '禁用';
                    }},
                    {field: 'createTime', title: '创建时间', width: 150, templet: function(d) {
                        return d.createTime ? new Date(d.createTime).toLocaleString() : '';
                    }},
                    {title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#authorBar'}
                ]],
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100]
            });

            // 绑定表格工具条事件
            table.on('tool(authorTable)', function(obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    showAuthorDialog(data);
                } else if (obj.event === 'del') {
                    layer.confirm('确定删除此作者？', function(index) {
                        $.post('/author/delete', {id: data.id}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                obj.del();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });

            // 绑定工具栏按钮事件
            table.on('toolbar(authorTable)', function(obj) {
                if (obj.event === 'add') {
                    showAuthorDialog();
                } else if (obj.event === 'batchDel') {
                    var checkStatus = table.checkStatus('authorTable');
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg('请选择要删除的数据', {icon: 2});
                        return;
                    }
                    
                    var ids = data.map(function(item) {
                        return item.id;
                    });
                    
                    layer.confirm('确定要删除选中的作者吗？', function(index) {
                        $.post('/author/deleteBatch', {ids: ids}, function(res) {
                            if (res.code === 200) {
                                layer.msg('删除成功', {icon: 1});
                                tableIns.reload();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2});
                            }
                        }).fail(function() {
                            layer.msg('网络错误，请稍后重试', {icon: 2});
                        });
                        layer.close(index);
                    });
                }
            });
        });
    }
}

// 显示作者对话框
function showAuthorDialog(data) {
    var title = data ? '编辑作者' : '新增作者';
    var authorHtml = `
        <form class="layui-form" id="authorForm" style="padding: 20px;">
            <input type="hidden" name="id" value="${data ? data.id : ''}">
            <div class="layui-form-item">
                <label class="layui-form-label">作者姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="请输入作者姓名" value="${data ? data.name : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">国籍</label>
                <div class="layui-input-block">
                    <input type="text" name="nationality" placeholder="请输入国籍" value="${data ? data.nationality : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="email" name="email" placeholder="请输入邮箱" value="${data ? data.email : ''}" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <select name="status">
                        <option value="1" ${data && data.status === 1 ? 'selected' : ''}>启用</option>
                        <option value="0" ${data && data.status === 0 ? 'selected' : ''}>禁用</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">简介</label>
                <div class="layui-input-block">
                    <textarea name="biography" placeholder="请输入作者简介" class="layui-textarea">${data ? data.biography : ''}</textarea>
                </div>
            </div>
        </form>
    `;

    layui.use(['layer', 'form'], function() {
        var layer = layui.layer;
        var form = layui.form;
        
        var dialog = layer.open({
            type: 1,
            title: title,
            area: ['500px', '500px'],
            content: authorHtml,
            btn: ['确定', '取消'],
            success: function(layero, index) {
                form.render();
            },
            yes: function(index, layero) {
                var formData = form.val('authorForm');
                
                // 发送请求
                var url = formData.id ? '/author/update' : '/author/add';
                $.post(url, formData, function(res) {
                    if (res.code === 200) {
                        layer.msg(formData.id ? '修改成功' : '添加成功', {icon: 1});
                        layer.close(index);
                        // 重新加载表格
                        if (typeof layui !== 'undefined' && layui.table) {
                            layui.table.reload('authorTable');
                        }
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                }).fail(function() {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                });
            }
        });
    });
}